package com.twu.biblioteca.dao;

import com.twu.biblioteca.model.Item;
import com.twu.biblioteca.model.ItemStatus;

import java.util.ArrayList;
import java.util.List;

public class ItemDao {
    private List<ItemStatus> itemStatusLists = new ArrayList<>();
    private ItemDaoStrategy strategy;

    public ItemDao(ItemDaoStrategy strategy) {
        this.setStrategy(strategy);
    }

    public void prepareData() {
        List<Item> items = strategy.getInitialData();
        for (Item item : items) {
            addItem(item);
        }
    }

    public List<Item> getAvailableItemLists() {
        ArrayList<Item> availableItemLists = new ArrayList<>();
        for (ItemStatus itemStatus : itemStatusLists) {
            if (itemStatus.getIsAvailable()) {
                availableItemLists.add(itemStatus.getItem());
            }
        }
        return availableItemLists;
    }

    public List<Item> getUnavailableItemLists() {
        ArrayList<Item> unavailableItemLists = new ArrayList<>();
        for (ItemStatus itemStatus : itemStatusLists) {
            if (!itemStatus.getIsAvailable()) {
                unavailableItemLists.add(itemStatus.getItem());
            }
        }
        return unavailableItemLists;
    }

    public void addItem(Item item) {
        ItemStatus itemStatus = new ItemStatus(item, true);
        itemStatusLists.add(itemStatus);
    }

    public void checkoutItem(Item item) {
        int index = itemStatusLists.indexOf(new ItemStatus(item, true));
        ItemStatus itemStatus = itemStatusLists.get(index);
        itemStatus.setIsAvailable(false);
    }

    public void returnItem(Item item) {
        int index = itemStatusLists.indexOf(new ItemStatus(item, false));
        ItemStatus itemStatus = itemStatusLists.get(index);
        itemStatus.setIsAvailable(true);
    }

    public void setStrategy(ItemDaoStrategy strategy) {
        this.strategy = strategy;
    }
}
